<?php
/**
 * Created by PhpStorm.
 * User: lyang
 * Date: 2016/12/31
 * Time: 13:15
 */


class Router
{
    public function run( )
    {
        $uri    = $_SERVER["REQUEST_URI"];
        $iParam = parse_url($uri);
        $iParam = explode("/", $iParam["path"]);
        #没有uri重写的情况
        if ($iParam[1] == "index.php") {
            array_shift($iParam);
        }
        $uri = function($name){
            return sprintf(
                "%s/src/%s.php",
                ROOT,
                $name
            );
        };
        $first   = isset($iParam[1]) && !empty($iParam[1]) ? $iParam[1] : "default";
        $second = isset($iParam[2]) && !empty($iParam[2]) ? $iParam[2] : "index";
        if(is_file($uri("$first/$second"))){
            $i_uri = $uri("$first/$second");
            goto SUCCESS;
        }else if(is_file($uri("$first"))){
            $i_uri = $uri($first);
            goto SUCCESS;
        }
        YC::location(YC::get("ROOT")."/p/404.html");
        exit("$first  $second not found");
        SUCCESS:
        return require_once "$i_uri";
    }
    public function admin( )
    {
        $uri    = $_SERVER["REQUEST_URI"];
        $iParam = parse_url($uri);
        $iParam = explode("/", $iParam["path"]);
        #没有uri重写的情况
        if ($iParam[1] == "admin.php") {
            array_shift($iParam);
        }
        $uri = function($name){
            return sprintf(
                "%s/admin/%s.php",
                ROOT,
                $name
            );
        };
        $first   = isset($iParam[1]) && !empty($iParam[1]) ? $iParam[1] : "default";
        $second = isset($iParam[2]) && !empty($iParam[2]) ? $iParam[2] : "index";
        if(is_file($uri("$first/$second"))){
            $i_uri = $uri("$first/$second");
            goto SUCCESS;
        }else if(is_file($uri("$first"))){
            $i_uri = $uri($first);
            goto SUCCESS;
        }
        YC::location(YC::get("ROOT")."/p/404.html");
        SUCCESS:
        return require_once "$i_uri";
    }
}